home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 10552 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: druid.borland.com!usenet
  2. From: pete@borland.com (Pete Becker)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Determining the length of an int in string form
  5. Date: 18 Mar 1996 15:38:12 GMT
  6. Organization: Borland International
  7. Message-ID: <4ik014$5cn@druid.borland.com>
  8. References: <3146D058.DD7@cbm.com>
  9. NNTP-Posting-Host: pbecker.borland.com
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=ISO-8859-1
  12. X-Newsreader: WinVN 0.99.5
  13.  
  14. In article <3146D058.DD7@cbm.com>, paynedc@cbm.com says...
  15. >
  16. >Consider this:
  17. >
  18. >I have a variable of type int, and I would like to use the sprintf() 
  19. >function to write this variable to a string.  However, I want to 
  20. >dynamically allocate the space for the string, and only malloc enough 
  21. >space to hold the int.  Here's a code fragment that may illustrate this 
  22. >more clearly:
  23. >
  24. >void func1()  {
  25. >
  26. >  int    i = 1234;
  27. >  char  *a;
  28. >
  29. >  /* 
  30. >   * We need to malloc enough space to hold "The value of i is"
  31. >   *  AND 1234.  The 4 + 1 is for the 4 bytes that 1234 will occupy
  32. >   * in the string, and for a NULL terminator.
  33. >   */
  34. >  a = malloc(strlen("The value of i is ") + 4 + 1);
  35. >  
  36. > /*
  37. >   * Use sprintf() to build the desired string.
  38. >   */                                                                    
  39. >  
  40. >  sprintf(a,"%s%d","The value of i is ",i);
  41. >
  42. >  free(a);
  43. >
  44. >}
  45. >
  46. >In this example, I hardcoded the 4, because I knew that 1234 was 4 
  47. >characters long.  I would like to be able to determine this at runtime, 
  48. >and malloc enough space accordingly.
  49.  
  50. This is not hard. Think about it. How many characters are needed to display a 
  51. value that's between 1000 and 9999? How many are needed to display a value 
  52. that's between 10000 and 99999? See the pattern? Add one for a possible minus 
  53. sign, and one more for the terminating 0. Or make your life simpler and 
  54. allocate an array that's large enough to hold the text for any number. The 
  55. space savings from doing this are rarely worth the aggravation.
  56.     -- Pete
  57.  
  58.  
  59.